'use strict';

const Controller = require('egg').Controller;
const { getCookieValue } = require('../public/processCookies');
const { axios } = require('../public/httpHelper');
const qs = require('qs');
const configDefault = require('../../config/config.default')();
/**
* @controller TenantAdminController 注释必写，swagger-doc是根据这段注释来生成接口的 ）。
*/
class TenantAdminController extends Controller {
  // 查询
  async list() {
    /**
    * @summary 租户列表分页。
    * @description 租户列表分页。
    * @router get /tenantadminlist
    * @request query integer limit
    * @request query integer page
    * @request query string serach
    */
    const params = this.ctx.query;
    const config = {
      method: 'get',
      url: `${configDefault.authorization.url}/tenant?limit=${params.limit}&page=${params.page}${params.search ? '&search=' + params.search : ''}`,
      // httpsAgent: agent,
    };
    try {
      const response = await axios(config);
      this.ctx.body = {
        msg: '',
        status: 200,
        data: response.data.rows,
        count: response.data.count,
      };
    } catch (error) {
      console.log(error);
      this.ctx.body = {
        msg: error,
        status: 500,
        data: null,
        count: 0,
      };
    }
    // const result = await this.ctx.service.tenantAdmin.tenantAdminList(params);
  }
  // 添加tenantAdmin
  async add() {
    /**
    * @summary 租户添加。
    * @description 租户添加。
    * @router post /tenantadmincreate
    * @request body tenantadmincreate value 传入参数
    */
    const params = this.ctx.request.body;
    // 查询代理名字是否存在
    const result = await this.ctx.service.tenantAdmin.tenantAdminSingle(params.name);
    if (!result) {
      await this.ctx.service.tenantAdmin.tenantAdminCreate(params);
      this.ctx.body = {
        msg: 'create tenantadmin successful',
        status: 5,
      };
    } else {
      this.ctx.body = {
        status: 4,
        msg: 'The username is exits',
      };
    }
  }
  // //修改tenantAdmin
  async edit() {
    /**
    * @summary 租户添加。
    * @description 租户添加。
    * @router post /tenantadminedit
    * @request body tenantadminedit value 传入参数
    */
    const params = this.ctx.request.body;
    await this.service.tenantAdmin.tenantAdminEdit(params);
    this.ctx.body = {
      msg: 'edit tenantadmin successful',
      status: 6,
    };
  }
  async acsInit() {
    /**
    * @summary 租户添加ACS。
    * @description 租户添加ACS。
    * @router post /tenantadminInitACS
    * @request body tenantadminInitACS value 传入参数
    */
    const params = this.ctx.request.body;
    const data = qs.stringify({
      tenantid: params.id,
      acsURL: params.url,
    });
    const config = {
      method: 'post',
      url: `${configDefault.authorization.url}/updateACS`,
      data,
    };
    try {
      const response = await axios(config);
      console.log(response);
      // await this.service.tenantAdmin.acsInit(params);
      this.ctx.body = {
        msg: 'tenantadmin successful',
        status: 10,
      };

    } catch (error) {
      this.ctx.body = {
        msg: 'tenantadmin fail',
        status: 10,
      };
    }
  }
  // 删除tenantAdmin
  async delete() {
    /**
    * @summary 租户删除。
    * @description 租户删除。
    * @router get /tenantadmindelete
    * @request query string id
    */
    const params = this.ctx.query;
    await this.service.tenantAdmin.tenantAdminDelete(params);
    this.ctx.body = {
      msg: 'delete tenantadmin successful',
      status: 7,
    };
  }
  async init() {
    /**
    * @summary tenantadmininit
    * @description tenantadmininit
    * @router get /tenantadmininit
    * @request query string id
    */
    const params = this.ctx.query;
    const data = qs.stringify({
      tenantid: params.id,
    });
    const config = {
      method: 'post',
      url: `${configDefault.authorization.url}/findSuperByTenant`,
      data,
    };
    const response = await axios(config);
    const userid = response.data.id;
    const result = await this.service.tenantAdmin.tenantAdminInit(params, userid);
    if (result == true) {
      this.ctx.body = {
        msg: 'init tenantadmin successful',
        status: 8,
      };
    } else {
      this.ctx.body = {
        msg: 'init tenantadmin fail',
        status: 9,
      };
    }
  }
  async tr069Init() {
    /**
    * @summary tenantadmintr069init
    * @description tenantadmintr069init
    * @router get /tenantadmintr069init
    * @request query string id
    */
    const params = this.ctx.query;
    const result = await this.service.tenantAdmin.tenantAdmintr069Init(params);
    if (result == true) {
      this.ctx.body = {
        msg: 'init tenantadmin tr069 successful',
        status: 8,
      };
    } else {
      this.ctx.body = {
        msg: 'init tenantadmin tr069 fail',
        status: 9,
      };
    }
  }
  // 获取租户
  async listAll() {
    /**
    * @summary 所有租户。
    * @description 所有租户。
    * @router get /tenantadminlistall
    */
    const result = await this.ctx.service.tenantAdmin.tenantAdminListAll();
    this.ctx.body = {
      msg: '',
      status: 200,
      data: result.rows,
      count: result.count,
    };
  }
  // 修改密码
  async editPassword() {
    /**
    * @summary 修改密码
    * @description 修改密码
    * @router post /tenanteditpassword
    * @request body editpassword value 传入参数
    */
    const params = this.ctx.request.body;
    await this.ctx.service.tenantAdmin.editPassword(params);
    this.ctx.body = {
      msg: 'edit password successful',
    };
  }
  async single() {
    /**
    * @summary tenantsingle
    * @description tenantsingle
    * @router get /tenantsingle
    */
    const { id } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    // const result = await this.ctx.service.tenantAdmin.single();
    const config = {
      url: `${configDefault.authorization.url}/getTenant?tenantid=${id}`,
      method: 'get',
    };
    const response = await axios(config);
    console.log(response);
    if (response && response.data) {
      this.ctx.body = {
        data: {
          ftpIp: response.data.ftpIp,
          ftpPassword: response.data.ftpPassword,
        },
      };
    } else {
      this.ctx.body = {
        data: null,
      };
    }
  }
  async tenantftpedit() {
    /**
    * @summary 修改ftp
    * @description 修改ftp
    * @router post /tenantftpedit
    * @request body editftp value 传入参数
    */
    const { ftpIp, ftpPassword } = this.ctx.request.body;
    const accessToken = getCookieValue(this.ctx.cookies, 'token', 'accessToken');
    const { id: tenantid } = getCookieValue(this.ctx.cookies, 'token', 'tenant');
    console.log(accessToken);
    const data = qs.stringify({
      ftpIp,
      ftpPassword,
      tenantid,
    });
    const config = {
      method: 'post',
      url: `${configDefault.authorization.url}/updateFTP`,
      headers: {
        // Authorization: 'Bearer bd79a645f3a2c7920c02f7bd7e2da1b37eed6b88',
        Authorization: `Bearer ${accessToken}`,
      },
      data,
    };
    try {
      const response = await axios(config); // 请求接口
      this.ctx.body = {
        code: 200,
        msg: 'edit password successful',
      };
    } catch (err) {
      if (err.code === 401) {
        const refreshToken = getCookieValue(this.ctx.cookies, 'token', 'refreshToken');
        const data = qs.stringify({
          grant_type: 'refresh_token',
          client_id: 'hyewfbgawd',
          client_secret: 'fskefgtarwdbawydrawpdpaiuiawdtg',
          refresh_token: refreshToken,
        });
        const refreshConfig = {
          method: 'post',
          url: `${configDefault.authorization.url}/users/token`,
          data,
        };
        try {
          const res = await axios(refreshConfig);
          console.log(res);
          this.ctx.cookies.set('token', JSON.stringify(res.data), {
            maxAge: 1000 * 3600 * 24, // cookie存储一天 设置过期时间后关闭浏览器重新打开cookie还存在
            httpOnly: true, // 仅允许服务获取,不允许js获取
            signed: true, // 对cookie进行签名 防止用户修改cookie
            encrypt: true, // 是否对cookie进行加密 如果cookie加密那么获取的时候要对cookie进行解密
            // domain: 'haha.com',
            path: '/',
            secure: false,
          });
          config.headers = { Authorization: `Bearer ${res.data.accessToken}` };
        } catch (error) {
          console.log(error);
        }
        const resp = await axios(config);
        this.ctx.body = {
          code: 200,
          msg: 'edit password successful',
        };

      }
    }


    // await this.ctx.service.tenantAdmin.tenantftpedit(params);
  }
  async cloudOltServerInit(){
    /**
    * @summary tenantadminInitCloudOltServer
    * @description tenantadminInitCloudOltServer
    * @router get /tenantadminInitCloudOltServer
    * @request body tenantadminInitCloudOltServer value 传入参数
    */
   const result = {
     flag:false,
     msg:''
   }
     const params = this.ctx.request.body;
     const data = qs.stringify({
      cloudOltURL:params.url,
      cloudOltState:params.state,
      cloudOltUsername:params.username,
      cloudOltPassword:params.password,
      tenantid: params.id,
    });
     const config = {
      method: 'post',
      url: `${configDefault.authorization.url}/updateCloudOltServer`,
      data,
    };
    //  const result = await this.ctx.service.tenantAdmin.cloudOltServerInit(params);
     const response = await axios(config);
      console.log(response);
      if(response.status===200){
        result.flag = true;
        if(response.data[0]===1){
          result.msg="success"
        }else{
          result.msg="false"
        }
      }
     this.ctx.body=result;
  }
}

module.exports = TenantAdminController;
